<?php

namespace App\Http\Controllers\Home;

use App\Models\Cates;
use App\Models\Configs;
use App\Models\Lives;
use App\Models\News;
use App\Models\Praises;
use App\Models\Seos;
use App\Models\Tags;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class NewController extends Controller
{
    protected $chanel_id = 2;//设置导航选中标志

    public function __construct()
    {
        view()->share('chanel_id',$this->chanel_id);
        view()->share('news_position',$this->getNewPosition());
        view()->share('news_hot',$this->getNewHot());
        view()->share('authors',$this->getAuthor());
        view()->share('lives_position',$this->getLivePosition());
        view()->share('seo',Seos::seo('SEO-NEW'));
    }

    //首页
    public function index(Request $request)
    {
        //查询新闻类目
        $news_category = Cates::categories(1000);
        $params = [
            'catepid'  => (int)$request->get('catepid',0),
            'title'  => (string)$request->get('title',''),
            'cateid'  => (int)$request->get('cateid',0),
            'position'  => (int)$request->get('position',0),//为1，则查询所有推荐
            'status'    => News::STATUS_1,
        ];
        $fields = ['id','title','summary','view','created_at','thumb','cateid','author_id','catepid','praise'];
        $lists = News::home($fields,$params,10);
        if($request->ajax()){
            return $this->writeJson(0,$lists);
        }
        return view('home.new.index',compact('news_category'));
    }

    //详情
    public function info(Request $request)
    {
        $id = (int)$request->get('id',0);
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        $fields = ['id','title','thumb','author_id','catepid','cateid','content','state','tags','view','praise','created_at'];
        $params = [
            'status' => News::STATUS_1
        ];
        $info = News::findOne($id,$fields,$params);

        if($info['tags'] && count($info['tags'])){
            $tags = Tags::newTags($info['tags']);
            $info['tags'] = $tags;
        }

        // 获取下一篇
        $next = News::next($id);

        // 相关资讯
        $about_news = News::aboutNews($id);

        // 用户数据
        $user_news = News::userNews($info['author_id']);

        // 统计浏览量
        $info->increment('view');

        //统计文章数
        $total_news = News::countNews($info['author_id']);

        //统计浏览量
        $total_views = News::countViews($info['author_id']);

        return view('home.new.info',compact('info','prev','next','about_news','user_news','total_news','total_views'));
    }

    public function praise(Request $request){
        $id = (int)$request->get('id',0);
        if(empty($id)) return $this->writeJson(1,null,'参数错误');
        if(auth()->guest())  return $this->writeJson(1,null,'未登录');
        $num = Praises::incPraise($id);
        return $this->writeJson(0,$num);
    }

}